/*
 * @Author: your name
 * @Date: 2022-03-28 14:39:23
 * @LastEditTime: 2022-05-03 09:20:36
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \VScodeToWeb\bookWebApi\util\common.js
 */
const mydebug = require('debug')('expressjs:[系统调试信息]')
var md5 = require('blueimp-md5')//让密码输入时加密
var config = require('../config')


/**
 * 格式化输出
 * code 200 访问成功
 * code 400 访问失败
 */
// util.getReturnJSONData = function(code, message='', data = []){
function getReturnJSONData(code, message='', data = []){
    if(!data)
        data = [];//如果进来为加，就变成 alt+shift +F 代码会字段排版
    return{code, message:message, data:data };//return end
}//getReturnJSONData end


/**
 * 调式信息
 * @param {*} msg 
 */
function log(msg) {
    debug(msg);
    
}


/**
 * 生成md5后的密码
 * @param {String} password
 * @returns {String} password
 */
function md5pwd(password) {
    // md5加盐加密
    return md5(password, config.salt)
  }
  
  /**
   * 获取客户端IP地址
   * @param {Express.Request} req
   * @returns {String} ip
   */
  function getReqRemoteIp(req) {
    return (req.headers['x-forwarded-for'] || '').split(',')[0] || req.ip
  }
  
  /**
   * 登录检测
   * @param {express.Request} req
   * @param {express.Response} res
   * @param {express.NextFunction} next
   */
  function checkLogin(req, res, next) {
    if (!req.session.isLogin) {
      res.json(getReturnJSONData(401, '无访问授权'))
    } else {
      log(req.session.user)
      next()
    }
  }
  
  /**
   * 登录检测
   * @param {express.Request} req
   * @param {express.Response} res
   * @param {express.NextFunction} next
   */
  function checkIsAdmin(req, res, next) {
    if (req.session.user.role !== 1) {
      res.json(getReturnJSONData(403, '无访问权限'))
    } else {
      log(req.session.user)
      next()
    }
  }

// module.exports = util;
module.exports = {
    getReturnJSONData,
    log,
    md5pwd,
    getReqRemoteIp,
    checkLogin,
    checkIsAdmin,
};



